import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { createWriteStream } from 'fs';
import { FileUpload } from 'graphql-upload';
import { checksumFile } from 'src/utils/checksumFile';
import * as path from 'path';
import * as co from 'co'
import OSS from 'ali-oss'
import * as fs from 'fs'

@Injectable()
export class UploadService {
//   async fileUpload(file: FileUpload): Promise<string> {
//     console.log(file, '上传的文件', __dirname, process.cwd());   
//     console.log(file, '上传的文件');
//     const { createReadStream, filename } = file;
//     console.log('q')
//     const md5FileName = await checksumFile('md5', createReadStream);
//     // 获取文件的扩展名
//     const extname = path.extname(filename).toLocaleLowerCase();
//     new Promise(async (resolve, reject) =>
//       createReadStream()
//         .pipe(createWriteStream(`${process.cwd()}/client/uploads/${md5FileName}${extname}`))
//         .on('finish', () => resolve(true))
//         .on('error', () => reject(false))
//     );
//     // 先就这样写死
//     return `localhost:3000/client/uploads/${filename}`;
//   }

  async fileUpload(file: FileUpload): Promise<string> {
    const { filename, createReadStream } = file;
    // 使用md5的方式处理图片
    const md5FileName = await checksumFile('md5', createReadStream);
    // 获取文件的扩展名
    const extname = path.extname(filename).toLocaleLowerCase();
    // 请自行替换成自己的
    const client = new OSS({
      region: 'oss-cn-shanghai',
      accessKeyId: 'LTAI4',
      accessKeySecret: 'Skux',
      bucket: 'box',
      secure: true, // 开启https
    });
    return await co(function* () {
      client.useBucket('dance-box'); //自定义项
      const result = yield client.put(`uploads/${md5FileName}${extname}`, createReadStream());
      return result.url;
    }).catch((err: HttpException) => {
      throw new HttpException(err, HttpStatus.OK);
    });
  }
}